$(function () {
    //定义全局变量
    window.pageSize = 5;
    window.pageNum = 1;
    window.keyword = "";
    //在全局作用域内创建roleIdArray
    window.roleIdArray = new Array();
    //显示数据
    showPage();
    //查询
    $("#searchBtn").click(function () {
        //获取keyword
        var keyword = $("#keywordInput").val();
        //验证
        if (keyword.length == 0) {
            layer.msg("请填写关键字");
            return;
        }
        //更新全局变量
        window.keyword = keyword;
        //更新数据
        showPage();

    });

    // 全选/全不选功能
    $("#summaryBox").click(function () {
        // 1.获取当前checkbox的选中状态
        var currentStatus = this.checked;
        // 2.设置itemBox的选中状态
        $(".itemBox").prop("checked", currentStatus);

    });
    //删除
    $("#batchRemoveBtn").click(function () {
        // 获取选中的roleid
        var length = $(".itemBox:checked").length;
        // 判断是否有数据
        if (length == 0) {
            layer.msg("请至少选择一行数据！");
            return;
        }
        $(".itemBox:checked").each(function () {
            var roleid = $(this).attr("roleid");
            window.roleIdArray.push(roleid);
        });
        // 调用函数打开模态框
        showRemoveConfirmModal();
    });
    //单条删除
    $("#roleTableBody").on('click', '.removeBtn', function () {
        var roleid = $(this).attr("roleid");
        window.roleIdArray.push(roleid);
        //打开模态框
        showRemoveConfirmModal();

    })
    //确认删除
    $("#confirmModalBtn").click(function () {
        var requestBody = JSON.stringify(window.roleIdArray);
        $.ajax({
            url: "/role/batch/remove",
            type: "post",
            data: requestBody,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (ajaxResult) {

                if (ajaxResult.result == "SUCCESS") {
                    // 如果删除成功，则重新调用分页方法
                    showPage();
                } else {
                    layer.msg("删除失败")
                }
                // 不管成功还是失败，都需要关掉模态框
                $("#confirmModal").modal("hide");
            },
        });
    });

    //添加
    $("#addBtn").click(function () {
        $("#addModal").modal("show");
    });
    //保存
    $("#addModalBtn").click(function () {
        // 1.收集文本框内容
        var roleName = $.trim($("#roleNameInput").val());
        if (roleName.length==0) {
            layer.msg("用户角色不能为空");
            return;
        }
        $.ajax({
            url: "/role/save/role",
            type: "post",
            data: {
                "roleName": roleName
            },
            dataType: "json",
            success: function (ajaxResult) {
                var result = ajaxResult.result;
                if (result == "SUCCESS") {
                    showPage();
                } else {
                    layer.msg("添加失败");
                }
                $("#addModal").modal("hide");
            }
        });
    });
    //修改
    $("#roleTableBody").on("click",".editBtn",function(){
        // 1.获取当前按钮的roleId
        window.roleId = $(this).attr("roleId");
        // 2.获取当前按钮所在行的roleName,回显到文本框
        var roleName = $(this).parent("td").prev().text();
        // 3.修改模态框中文本框的value值，目的是在显示roleName
        $("#roleNameInputEdit").val(roleName);
        // 4.打开模态框
        $("#editModal").modal("show");
    });
    //确认修改
    $("#editModalBtn").click(function () {
        // 1.获取文本框值
        var roleName = $("#roleNameInputEdit").val();
        if(roleName.length==0) {
            layer.msg("用户角色不能为空！");
            return ;
        }
        $.ajax({
            url:"/role/update/role",
            type:"post",
            data:{
                "id":window.roleId,
                "name":roleName
            },
            dataType:"json",
            success:function (ajaxResult) {
                if(ajaxResult.result == "SUCCESS") {
                    // 3.操作成功重新分页
                    showPage();
                }else{
                    layer.msg("添加失败");
                }
                // 4.不管成功还是失败，关闭模态框
                $("#editModal").modal("hide");
            }
        });
    });
    //绑定修改权限按钮单击事件
    $("#roleTableBody").on("click",".checkBtn",function(){
        // 将角色id存入全局变量
        window.roleId = $(this).attr("roleId");
        $("#roleAssignAuthModal").modal("show");
        //初始化ztree
        initWholeTree();

    });

//初始化zTree
    function initWholeTree(){
        var setting = {
            "data": {
                "simpleData": {
                    "enable": true,
                    "pIdKey": "categoryId"
                },
                "key": {
                    "name": "title"
                }
            },
            "check": {
                "enable": true//数据前的复选框
            }
        };
        // 2.获取JSON数据
        $.ajax({
            "url": "/assign/get/all/auth",
            "type": "post",
            "dataType": "json",
            success:function (ajaxResult) {
                if(ajaxResult.result == "FAILED") {
                    layer.msg(ajaxResult.message);
                    return ;
                }
                var zNodes = ajaxResult.data;
                // 3.初始化树形结构
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                //展开所有节点
                $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);
            }
        });
    }
打开删除的模态框
    function showRemoveConfirmModal() {
        $("#confirmModal").modal("show");
        var requestBody = JSON.stringify(window.roleIdArray);
        $.ajax({
            url: "/role/get/list/by/id/list",
            type: "post",
            data: requestBody,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (ajaxResult) {
                if (ajaxResult.result == "SUCCESS") {
                    $('#confirmModalTableBody').empty();
                    //渲染数据
                    var list = ajaxResult.data;
                    for (var i = 0; i < list.length; i++) {
                        var tr = $('<tr></tr>');
                        var td1 = $('<td>' + (i + 1) + '</td>');
                        var td3 = $('<td>' + list[i].name + '</td>');

                        tr.append(td1);
                        tr.append(td3);
                        $("#confirmModalTableBody").append(tr);
                    }
                } else {
                    layer.msg("删除数据失败！");
                }
            }
        })
    }

    function showPage() {
        $.ajax({
            url: "/role/search/by/keyword",
            type: "post",
            data: {
                "pageNum": window.pageNum,
                "pageSize": window.pageSize,
                "keyword": window.keyword
            },
            dataType: "json",
            success: function (ajaxResult) {
                if (ajaxResult.result == "SUCCESS") {
                    var list = ajaxResult.data.list;
                    //清空旧数据
                    $("#roleTableBody").empty();
                    if (list.length == 0) {
                        //没数据
                        var tr = $('<tr></tr>');
                        var td = $('<td colspan="4">没有查询到数据！</td>');
                        tr.append(td);
                        $("#roleTableBody").append(tr);
                    } else {
                        //有数据
                        for (var i = 0; i < list.length; i++) {
                            var tr = $('<tr></tr>');
                            var td1 = $('<td>' + (i + 1) + '</td>');
                            var td2 = $('<td><input roleid="' + list[i].id + '" class="itemBox" type="checkbox"></td>');
                            var td3 = $('<td>' + list[i].name + '</td>');
                            var td4 = $('<td></td>');
                            var btn1 = $('<button roleId="' + list[i].id + '" type="button" class=" checkBtn btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>');
                            var btn2 = $('<button roleId="' + list[i].id + '" type="button" class="btn btn-primary btn-xs editBtn"><i class=" glyphicon glyphicon-pencil"></i></button>');
                            var btn3 = $('<button roleid="' + list[i].id + '" type="button" class="btn btn-danger btn-xs removeBtn"><i class=" glyphicon  glyphicon-remove"></i></button>');
                            td4.append(btn1);
                            td4.append(btn2);
                            td4.append(btn3);

                            tr.append(td1);
                            tr.append(td2);
                            tr.append(td3);
                            tr.append(td4);
                            $('#roleTableBody').append(tr);
                        }

                        initPagination(ajaxResult.data);
                    }
                }
            }
        });

    }

// 声明函数封装导航条初始化操作
    function initPagination(pageInfo) {
        // 声明变量存储总记录数
        var totalRecord = pageInfo.total;
        // 声明变量存储分页导航条显示时的属性设置
        var paginationProperties = {
            num_edge_entries: 3,        //边缘页数
            num_display_entries: 5,      //主体页数
            callback: pageselectCallback, //回调函数
            items_per_page: window.pageSize,    //每页显示数据数量，就是pageSize
            current_page: (window.pageNum - 1),//当前页页码
            prev_text: "上一页",       //上一页文本
            next_text: "下一页"        //下一页文本
        };
        // 显示分页导航条
        $("#Pagination").pagination(pageInfo.total, paginationProperties);
    }

// 在每一次点击“上一页”、“下一页”、“页码”时执行这个函数跳转页面
    function pageselectCallback(pageIndex, jq) {
        // pageIndex从0开始，pageNum从1开始
        window.pageNum = pageIndex + 1;
        var keyword = window.keyword;
        // 跳转页面
        showPage();
        return false;
    }
});